package org.tio.http.apitool;

import java.io.File;
import java.util.Objects;

import org.tio.http.common.HttpConfig;
import org.tio.http.server.HttpServerStarter;
import org.tio.http.server.handler.DefaultHttpRequestHandler;
import org.tio.server.ServerGroupContext;
import org.tio.utils.jfinal.P;

/**
 * @author tanyaowu
 */
public class HttpApiToolStarter {
	public static HttpConfig				httpConfig			= null;
	public static DefaultHttpRequestHandler	httpRequestHandler	= null;
	public static HttpServerStarter			httpServerStarter	= null;
	public static ServerGroupContext		serverGroupContext	= null;

	public static void main(String[] args) throws Exception {
		P.use("app.properties");
		httpConfig = new HttpConfig(P.getInt("http.port", 8086), 3600 * 24L, "", ".talent");
		httpConfig.setPageRoot(getPageRoot());
		httpConfig.setMonitorFileChange(true);
		httpRequestHandler = new DefaultHttpRequestHandler(httpConfig, HttpApiToolStarter.class.getPackage().getName());

		httpServerStarter = new HttpServerStarter(httpConfig, httpRequestHandler);
		serverGroupContext = httpServerStarter.getServerGroupContext();
		httpServerStarter.start();
	}

	/**
	 * 智能找路径
	 * @return
	 * @throws Exception
	 */
	private static String getPageRoot() throws Exception {
		String pageRoot = P.get("http.page");
		File file = new File(pageRoot);
		if (!file.exists()) {
			pageRoot = "./config/page";
			file = new File(pageRoot);
			if (!file.exists()) {
				String path = HttpApiToolStarter.class.getResource("/").toURI().getPath();
				String basePath = new File(path).getParentFile().getParentFile().getCanonicalPath();

				pageRoot = basePath + "/src/main/resources/page";
				file = new File(pageRoot);

				if (!file.exists()) {
					pageRoot = P.get("http.page");
				}
			}
		}

		if (file.exists() && !Objects.equals(P.get("http.page"),  pageRoot)) {
			System.out.println("在app.properties中配置的page目录不存在:" + P.get("http.page") + "\r\n已经自动帮你定位到:" + file.getCanonicalPath());
		}
		
		return pageRoot;
	}
}
